package cn.edu.xjtu.data_structure.chapter02_stack_queue.stack;

/**
 * @author yjq
 * @version 1.0
 * @date 2021/9/11 10:43
 */
public class AStack<T> implements StackADT<T> {
    //构造顺序栈
    private final int DTFAULT_SIZT = 10;
    private int size;//栈最多能容纳的元素个数
    private int top;//栈顶元素的下标
    private T[] listArray;//存储栈中元素的数组

    //初始化
    private void setUp(int size) {
        this.size = size;
        top = 0;
        listArray = (T[]) new Object[size];
    }

    //构造器
    public AStack() {
        setUp(DTFAULT_SIZT);
    }

    public AStack(int size) {
        setUp(size);
    }

    @Override
    public void clear() {
        top = 0;
    }

    @Override
    public void push(T it) {
        if (top >= size) {
            System.out.println("stack overflow");
            return;
        }
        listArray[top++] = it;
    }

    @Override
    public T pop() {
        if (isEmpty()){return null;}
        return listArray[--top];//top-1才是存储最顶元素的位置
    }

    @Override
    public T topValue() {
        if (isEmpty()){return null;}
        return listArray[top-1];
    }

    @Override
    public boolean isEmpty() {
        return top==0;
    }

    @Override
    public void print() {
        if (isEmpty()){
            System.out.println("empty");
        }
        for (int i=top-1;i>=0;i--){
            System.out.println(listArray[i]);
        }
    }

    @Override
    public int size() {
        return size;
    }
}
